import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

const Home = () => import('../views/Home')
const Cart = () => import('../views/Cart')
const Category = () => import('../views/Category')
const My = () => import('../views/My')
const Login = () => import('../views/Login')
const Reg = () => import('../views/Reg')
const Address = () => import('../views/Address')
const Collection = () => import('../views/Collection')
const Discount = () => import('../views/Discount')
const Message = () => import('../views/Message')
const Order = () => import('../views/Order')
const Scan = () => import('../views/Scan')
const GoodList = () => import('../views/Good/list.vue')
const GoodLists = () => import('../views/Good/goodLists.vue')
const Placeholder = () => import('../components/Layout/Placeholder.vue')

const routes = [
  {
    path: '/', name: 'placeholder', component: Placeholder,
    children: [
      { path: '', redirect: "/home" },
      { path: 'home', name: 'home', component: Home },
      { path: 'cart', name: 'cart', component: Cart },
      { path: 'category', name: 'category', component: Category },
      { path: 'my', name: 'my', component: My },
      { path: 'address', name: 'address', component: Address },
      { path: 'collection', name: 'collection', component: Collection },
      { path: 'discount', name: 'discount', component: Discount },
      { path: 'message', name: 'message', component: Message },
      { path: 'order', name: 'order', component: Order },
      { path: 'scan', name: 'scan', component: Scan },
      { path: 'GoodList/:catId?', name: 'GoodList', component: GoodList },
      { path: 'GoodLists/:goodListsId?', name: 'GoodLists', component: GoodLists },
    ]
  },
  { path: '/login', name: 'login', component: Login },
  { path: '/reg', name: 'reg', component: Reg },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//
router.beforeEach((to, from, next) => {
  let token = store.state.token;
  if (
    to.name == "order" ||
    to.name == "message" ||
    to.name == "collection" ||
    to.name == "address" ||
    to.name == "discount" ||
    to.name == "scan"
  ) {
    if (!token) {
      return next({path:'/login?back='+to.name})
    }
  }
  next()
})

export default router
